class Stock < ActiveRecord::Base
	has_many :users
	has_many :triggers
	has_many :ownerships
	validates_presence_of :name, :description, :face_value, :market_value
	validates_numericality_of :face_value, :market_value
	
	def self.freemex?
		stocks = Stock.open_stocks
		old_market_cap = new_market_cap = 0
		for stock in stocks
			old_price = History.first(:conditions => "stock_id = '#{stock.id}'").open
			old_market_cap += old_price * stock.quantity
			new_market_cap += stock.market_value * stock.quantity
		end
		freemex = (new_market_cap/old_market_cap)*1000

		return freemex
		rescue
			return 1000.0
	end
	
	def self.open_freemex?
		stocks = Stock.open_stocks
		old_market_cap = new_market_cap = 0
		for stock in stocks
			old_price = History.first(:conditions => "stock_id = '#{stock.id}'").open
			new_price = History.last(:conditions => "stock_id = '#{stock.id}'").open
			old_market_cap += old_price * stock.quantity
			new_market_cap += new_price * stock.quantity
		end
		freemex = (new_market_cap/old_market_cap)*1000

		return freemex
		rescue
			return 1000.0

	end

	def self.open_stocks
	  stocks = find(:all,
	       		:order      => "name asc")
	  open_stocks = []
	  for stock in stocks
		if Stock.status(stock) == 1
			open_stocks.push(stock)
		end
	  end
	  return open_stocks
	end
	def self.status(stock)
		status = Status.first(  :conditions => "stock_id = #{stock.id}" )
		if !status.nil?
			return status.open
		end
		return 0
	end
	def self.now
		tickers = Stock.open_stocks
		return tickers
	end
	protected
	def validate
	  errors.add(:face_value, "should be positive") unless face_value.nil? || face_value > 0.0
	  errors.add(:market_value, "should be positive") unless market_value.nil? || market_value > 0.0
	end

end
